/* eslint-disable react-hooks/exhaustive-deps */
import "./App.css";
import { useEffect, useRef, useState } from "react";
import BigMap from "./components/BbigMap";

function App() {
  const { pannellum, wx } = window;
  let [viewer, setViewer] = useState();
  const [showDialog, setShowDialog] = useState(false);
  const [deg, setDeg] = useState(0);
  const [currentScene, setCurrentScene] = useState("first");
  const count = useRef(0);
  const [showBigMap, setShowBigMap] = useState(false);
  const [isVr, setIsVr] = useState(null);
  useEffect(() => {
    viewer = pannellum.viewer("panorama", {
      default: {
        firstScene: "first",
        orientationOnByDefault: false, // 是否开启vr效果
        autoLoad: true, // 自动加载
        // autoRotate: -2, // 自动旋转
        // autoRotateInactivityDelay: 1000, // 用户操作页面后，自动旋转延迟
        friction: 0.15, // 控制摩擦器 0.1 到 1 值越大停的越快 默认值0.15
        showZoomCtrl: false, // 是否显示缩放控件
        showFullscreenCtrl: true, // 是否显示全屏控件
        touchPanSpeedCoeffFactor: 1, // 触摸时平移速度 默认1
        yaw: 0, // 垂直方向左右旋转角度 正值向右 负值向左
        pitch: -60, // 水平方向左右旋转角度 正值向上 负值向下 仰视太大 导致图片拉伸
        minPitch: -60, // 最小pitch 默认-180
        maxPitch: 60, // 最大pitch 默认180
        roll: 0, // z轴 横着的
        hfov: 60, // 摄像机视角
        minHfov: 10, // 摄像机最小视角
        maxHfov: 60, // 摄像机最大视角
        escapeHTML: true, // HTML 将从配置字符串中转义，以帮助缓解可能的 DOM XSS 攻击。
        crossOrigin: "anonymous", // 使用的 CORS 请求类型，可以设置为 anonymous或use-credentials。默认为anonymous.
        sceneFadeDuration: 1000, // 切换场景时动画持续时间
        // compass: true, // 指南针
        // northOffset: 90, // 指南针角度
        // horizonRoll: 10, // 指定图像水平的俯仰/滚动
        // hotSpotDebug: true, // 打印移动时的yaw pitch roll
        preview:
          "https://img.alicdn.com/imgextra/i4/O1CN014TNffn1nlaTfA98Fg_!!6000000005130-0-tps-1500-1500.jpg",
      },
      scenes: {
        first: {
          type: "cubemap", // 全景图类型
          cubeMap: [
            //立方体全景图六张图
            "https://img.alicdn.com/imgextra/i4/O1CN014TNffn1nlaTfA98Fg_!!6000000005130-0-tps-1500-1500.jpg",
            "https://img.alicdn.com/imgextra/i3/O1CN01LsO1Bk20QbKpFTUQr_!!6000000006844-0-tps-1500-1500.jpg",
            "https://img.alicdn.com/imgextra/i1/O1CN01sS5m781ya6JgLSaVk_!!6000000006594-0-tps-1500-1500.jpg",
            "https://img.alicdn.com/imgextra/i3/O1CN01uTWCLc1XOCOuA92H0_!!6000000002913-0-tps-1500-1500.jpg",
            "https://img.alicdn.com/imgextra/i4/O1CN016lU3YJ1JdrJuFTcWt_!!6000000001052-0-tps-1500-1500.jpg",
            "https://img.alicdn.com/imgextra/i2/O1CN01nYe2Mn1ohkmBVyKpp_!!6000000005257-0-tps-1500-1500.jpg",
          ],
        },
        second: {
          type: "cubemap",
          cubeMap: [
            require("./images/scene_back.jpeg"),
            require("./images/scene_right.jpeg"),
            require("./images/scene_front.jpeg"),
            require("./images/scene_left.jpeg"),
            require("./images/scene_top.jpeg"),
            require("./images/scene_bottom.jpeg"),
          ],
          hotSpots: [
            {
              pitch: 0,
              yaw: 20,
              type: "info",
              id: "one",
              text: "123",
              // image: "./images/hot.png",
            },
            {
              pitch: 20,
              yaw: 20,
              type: "scene",
              sceneId: "first",
              id: "two",
              text: "第一个画面",
              // image: "./images/hot.png",
            },
          ],
        },
      },
    });
    setViewer(viewer);

    console.log("viewer", viewer);
  }, []);
  function _handleSetDeg() {
    setDeg(viewer.getYaw());
  }
  // 监听load事件
  useEffect(() => {
    function test() {
      var test = document.querySelector(".test");
      console.log("test", test);
      if (!test) return;
      test.innerHTML =
        "这里是弹窗<div class='test-child'>点击可以打开弹窗</div>";
    }
    function addVideo() {
      var videoContainer = document.querySelector(".video-container");
      if (!videoContainer) return;
      var videoDiv = document.createElement("div");
      videoDiv.className = "video-div-container";
      var video = document.createElement("video");
      video.className = "video";
      video.src = "https://www.zuiaiwanqian.com/1.mp4";
      video.type = "video/mp4";
      // video.autoplay = true;
      // video.height = 230;
      // video.width = 300;
      video.controls = true;
      video.autobuffer = true;
      // video.muted = true;
      videoDiv.appendChild(video);
      videoContainer.appendChild(videoDiv);
      // setTimeout(() => {
      //   document.querySelector(".video").play();
      // }, 1000);
    }
    function loadTest() {
      if (count.current === 0) {
        const hs = {
          yaw: 10,
          pitch: 15,
          roll: -10,
          cssClass: "xiaochengxu",
          clickHandlerFunc: toXiaochengxu,
          scale: true,
        };
        const hs1 = {
          yaw: -30,
          pitch: -16,
          type: "scene",
          sceneId: "second",
          // id: "one",
          // text: "另一个画面",
          cssClass: "point",
          // image: "./images/hot.png",
          scale: true,
        };
        const hs2 = {
          yaw: -6,
          pitch: -26,
          cssClass: "test",
          clickHandlerFunc: clickTestBtn,
          scale: true,
        };
        const hs3 = {
          yaw: -72,
          pitch: 16,
          // roll: 10,
          cssClass: "video-container",
          scale: true,
        };
        viewer.addHotSpot(hs, "first");
        viewer.addHotSpot(hs1, "first");
        viewer.addHotSpot(hs2, "first");
        viewer.addHotSpot(hs3, "first");
        count.current += 1;
      }
      test();
      addVideo();
    }
    if (viewer) {
      // 监听viewer load
      // 第一个页面的hotSpot需要手动添加 否则会卡在页面上
      viewer.on("load", loadTest);
      return () => viewer.off("load", loadTest);
    }
  }, [viewer]);
  // 监听切换
  useEffect(() => {
    function changeScene(e) {
      setCurrentScene(e);
      setDeg(0);
    }
    // 监听切换
    viewer.on("scenechange", changeScene);
    return () => viewer.off("scenechange", changeScene);
  }, [viewer]);
  // 监听鼠标移动
  useEffect(() => {
    document.addEventListener("mousemove", _handleSetDeg);
    return () => document.removeEventListener("mousemove", _handleSetDeg);
  }, []);
  // 监听触摸
  useEffect(() => {
    document.addEventListener("touchmove", _handleSetDeg);
    return () => document.removeEventListener("touchmove", _handleSetDeg);
  }, []);
  // 监听陀螺仪
  useEffect(() => {
    window.addEventListener("devicemotion", _handleSetDeg);
    return () => window.removeEventListener("devicemotion", _handleSetDeg);
  }, []);
  // 在isVr变化时 重新监听拿到最新值 否则之前的监听拿不到最新值
  useEffect(() => {
    function startVr() {
      viewer.startOrientation();
    }
    if (viewer && isVr) {
      viewer.on("touchend", startVr);
      return () => viewer.off("touchend", startVr);
    }
  }, [viewer, isVr]);
  // 切换场景
  function handleChangeScene(scene) {
    if (scene !== currentScene) {
      viewer.loadScene(scene);
      setCurrentScene(scene);
    }
    setShowBigMap(false);
  }
  function clickTestBtn() {
    setShowDialog(true);
  }
  function toXiaochengxu() {
    wx.miniProgram.navigateTo({
      url: "/pages/index/index",
    });
  }
  function handleClickVr() {
    // 查看是否支持vr
    if (!viewer.isOrientationSupported()) {
      alert("当前设备不支持vr");
      setIsVr((pre) => {
        return !pre;
      });
      return;
    }
    // 如果当前是vr状态
    if (isVr) {
      viewer.stopOrientation();
      setIsVr(false);
    } else {
      viewer.startOrientation();
      setIsVr(true);
    }
  }
  return (
    <>
      <div>
        {/* 全景图容器 */}
        <div id="panorama"></div>
        {/* dialog */}
        {showDialog && (
          <div className="mask">
            这里是弹窗
            <div className="maskBtn" onClick={() => setShowDialog(false)}>
              X
            </div>
          </div>
        )}
        {/* 小地图 */}
        <div className="map-img" onClick={() => setShowBigMap(true)}>
          <img src={require("./images/map.png")} alt="" />
          <div className="map-img-div map-img-one">
            {currentScene === "first" && (
              <div
                className="fov"
                style={{ transform: `rotate(${deg}deg)` }}
              ></div>
            )}
          </div>
          <div className="map-img-div map-img-two">
            {currentScene === "second" && (
              <div
                className="fov"
                style={{ transform: `rotate(${deg}deg)` }}
              ></div>
            )}
          </div>
        </div>
        {/* 大地图 */}
        <BigMap
          scene={currentScene}
          onChangeScene={handleChangeScene}
          showBigMap={showBigMap}
          // 传递方法给子组件
          setShowBigMap={setShowBigMap}
        />
        {/* vr控制 */}
        <div className="mask-vr" onClick={handleClickVr}>
          {isVr ? "关闭vr" : "开启vr"}
        </div>
      </div>
    </>
  );
}

export default App;
